﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using SmallERP.Host.Frm;
using System.Configuration;
using System.ServiceModel.Configuration;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace SmallERP.Host
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool isAppRunning = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex(
                false,
                System.Diagnostics.Process.GetCurrentProcess().ProcessName,
                out isAppRunning);

            if (!isAppRunning)
            {
                MessageBox.Show("本程序已运行，请不要重复运行！");
                return;
            }
            try
            {
               // LayoutDll.ClassInterFace InterFace = new LayoutDll.ClassInterFace();
            }
            catch
            {
                MessageBox.Show("软件未授权请联系上海惟鸿网络", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Environment.Exit(1);
            }
            //修改服务的启动状态
            string serverErrorStr = "";
            int serverStatus = GetWindowsServiceStartType("NetTcpPortSharing", out serverErrorStr);
            if (serverStatus == 4)
            {
                if (SetWindowsServiceStartType("NetTcpPortSharing", 2))
                {

                }
                else
                {
                    MessageBox.Show("无法更改服务NetTcpPortSharing的启动类型，请手动修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //

                    Environment.Exit(1);
                }
            }
            else if (serverStatus == -1)
            {
                MessageBox.Show("无法更改服务NetTcpPortSharing的启动类型，请手动修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //
               
                Environment.Exit(1);
            }
            else
            {
 
            }
            int a=Modify();
            if (a == 0)
            {
                //MessageBox.Show("IP地址改变，请重新启动","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                //
                Application.Restart();
                Environment.Exit(1);
            }
            else if (a == -1)
            {
                MessageBox.Show("获取不到本机IP地址，请确认网络连接", "警告", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Environment.Exit(1);
            }
            else
            { }
             
            if(!File.Exists(Application.StartupPath+"\\MDB\\smallerp.mdb"))
            {
                if(!Directory.Exists(Application.StartupPath+"\\MDB"))
                {
                    Directory.CreateDirectory(Application.StartupPath + "\\MDB");
                }
                File.Copy(Application.StartupPath + "\\smallerp.mdb", Application.StartupPath + "\\MDB\\smallerp.mdb");
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmMain());
        }

        public static int Modify()
        {
            int rtnVal = 0;
            try
            {
                string computerName;
                IPAddress[] ipAddress;
                computerName = Dns.GetHostName();
                ipAddress = Dns.GetHostAddresses(computerName);

                string strIP = "";
                foreach (IPAddress ip in ipAddress)
                {
                    if (Regex.IsMatch(ip.ToString(), @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase))
                    {
                        strIP = ip.ToString();
                        break;
                    }

                }
                if (string.IsNullOrEmpty(strIP))
                {
                    strIP = "127.0.0.1";
                }
                DateTransfer.LocalIPadress = strIP;
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                ConfigurationSectionGroup sct = config.SectionGroups["system.serviceModel"];
                ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup;
                ServicesSection serverSection = serviceModelSectionGroup.Services;
                foreach (ServiceElement item in serverSection.Services)
                {

                    foreach (ServiceEndpointElement endpoint in item.Endpoints)
                    {
                        string pattern = "://.*/";
                        string address = endpoint.Address.ToString();
                        string oldHost = endpoint.Address.Host;
                        if (oldHost.Equals(strIP))
                        {
                            rtnVal = 1;//不要改变
                            break;
                        }
                        string replacement = string.Format("://{0}:{1}/", strIP, 7892);
                        address = Regex.Replace(address, pattern, replacement);
                        endpoint.Address = new Uri(address);
                    }
                    
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("system.serviceModel");
            }
            catch (Exception ex)
            {
                rtnVal = -1;
            }
            return rtnVal;
        }
        //取得服务的启动类型的当前状态，返回启动类型的状态値
        //2：自动，3：手动，4：禁用 ......
        //sServiceName服务名称
        //sState输出相关的状态代码，失败则为错误消息
        static int GetWindowsServiceStartType(String sServiceName, out String sState)
        {
            sState = "";

            try
            {
                System.Diagnostics.ProcessStartInfo objProcessInf = new System.Diagnostics.ProcessStartInfo();

                objProcessInf.FileName = "cmd.exe";

                objProcessInf.UseShellExecute = false;

                objProcessInf.RedirectStandardError = true;
                objProcessInf.RedirectStandardInput = true;
                objProcessInf.RedirectStandardOutput = true;

                objProcessInf.CreateNoWindow = true;

                objProcessInf.Arguments = "/c sc qc " + sServiceName;

                System.Diagnostics.Process objProcess = System.Diagnostics.Process.Start(objProcessInf);

                String sStateValue = objProcess.StandardOutput.ReadToEnd();

                if (sStateValue.IndexOf("AUTO_START") > 0)
                {
                    sState = "AUTO_START";
                    return 2;
                }

                if (sStateValue.IndexOf("DEMAND_START") > 0)
                {
                    sState = "DEMAND_START";
                    return 3;
                }

                if (sStateValue.IndexOf("DISABLED") > 0)
                {
                    sState = "DISABLED";
                    return 4;
                }

                return 0;

            }
            catch (Exception e)
            {
                sState = e.Message;
                return -1;
            }
        }
        //设置服务的启动类型
        //sServiceName服务名称
        //iStartType要设置的启动类型
        //返回成功状态 true：成功，false：失败
        static Boolean SetWindowsServiceStartType(String sServiceName, int iStartType)
        {
            try
            {
                System.Diagnostics.ProcessStartInfo objProcessInf = new System.Diagnostics.ProcessStartInfo();

                objProcessInf.FileName = "cmd.exe";

                objProcessInf.CreateNoWindow = false;
                objProcessInf.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

                string sStartState = "boot";

                switch (iStartType)
                {
                    case 1:
                        {
                            sStartState = "system";
                            break;
                        }
                    case 2:
                        {
                            sStartState = "auto";
                            break;
                        }
                    case 3:
                        {
                            sStartState = "demand";
                            break;
                        }
                    case 4:
                        {
                            sStartState = "disabled";
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }

                objProcessInf.Arguments = "/c sc config " + sServiceName + " start= " + sStartState;

                System.Diagnostics.Process.Start(objProcessInf);

                return true;
            }
            catch
            {
                return false;
            }
        } 
    }
}
